package com.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by zengliang on 17/6/24.
 */

public class CompareSortTest {

    public static void main(String[] args) throws Exception {

        List<DataBean> dataBeanList = new ArrayList<>();
        dataBeanList.add(new DataBean(1, 1));
        dataBeanList.add(new DataBean(2, 0));
        dataBeanList.add(new DataBean(3, 1));
        dataBeanList.add(new DataBean(4, 0));
        dataBeanList.add(new DataBean(5, 1));
        dataBeanList.add(new DataBean(6, 2));
        dataBeanList.add(new DataBean(7, 2));
        dataBeanList.add(new DataBean(8, 0));
        dataBeanList.add(new DataBean(9, 2));

        for (DataBean dataBean : dataBeanList) {
            System.out.println(dataBean.toString());
        }

        Comparator<DataBean> comparator = new Comparator<DataBean>() {
            @Override
            public int compare(DataBean o1, DataBean o2) {

                int serialId1 = o1.serialId == 0 ? o1.serialNo : o1.serialId;
                int serialId2 = o2.serialId == 0 ? o2.serialNo : o2.serialId;
                int flag = serialId1 - serialId2;
                if(flag == 0){
                    return o1.serialNo - o2.serialNo;
                } else {
                    return flag;
                }
            }
        };
        System.out.println("------------------------");


        Collections.sort(dataBeanList, comparator);
        for (DataBean dataBean : dataBeanList) {
            System.out.println(dataBean.toString());
        }
    }

    public static class DataBean{
        public int serialNo;
        public int serialId;

        public DataBean(int serialNo, int serialId) {
            this.serialNo = serialNo;
            this.serialId = serialId;
        }

        @Override
        public String toString() {
            return "serialNo = " + serialNo + ",serialId = " + serialId;
        }
    }
}
